package com.example.gkcircle.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.example.gkcircle.BaseActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.library.LibraryRequest;
import com.example.gkcircle.library.HttpRequest;
import com.example.gkcircle.library.object.GKUser;
import com.example.gkcircle.library.utils.AutoGetCaptcha;
import com.example.gkcircle.utils.MySVProgressHUD;
import com.example.gkcircle.utils.ToastFactory;
import com.example.gkcircle.widget.EditTextWithDelete;

/**
 * 绑定图书馆，教务处账号页  (保存账号)
 * Created by Jehu on 16/3/21.
 */
public class BoundLoginActivity extends BaseActivity implements View.OnClickListener{


    private EditTextWithDelete mUseridEdit;
    private EditTextWithDelete mOfficePswEdit;
    private EditTextWithDelete mLibraryPswEdit;
    private Button mLoginBtn;
    private ImageButton mCloseBtn;

    private Bitmap mCaptcha;
    private final String TAG="BoundLoginActivity";
    private final int MESSAGE_SUCCEED=0x000;
    private final int MESSAGE_WRONG=0x001;


    @Override
    protected void initView() {
        setContentView(R.layout.bound_login_activity);
        this.mUseridEdit=(EditTextWithDelete)this.findViewById(R.id.bound_login_userid_edit);
        this.mOfficePswEdit=(EditTextWithDelete)this.findViewById(R.id.bound_login_office_psw_edit);
        this.mLibraryPswEdit=(EditTextWithDelete)this.findViewById(R.id.bound_login_library_psw_edit);
        this.mLoginBtn=(Button)this.findViewById(R.id.bound_save_btn);
        this.mCloseBtn=(ImageButton)this.findViewById(R.id.bound_login_close_btn);
    }

    @Override
    protected void initListener() {
        mCloseBtn.setOnClickListener(this);
        mLoginBtn.setOnClickListener(this);
    }

    @Override
    protected void setData() {
        GKUser user=GKUser.getCurrentUser(this);
        if(user!=null){
            mUseridEdit.setText(user.getUserId());
            mLibraryPswEdit.setText(user.getPassword());
        }
        //先获取验证码
        getCaptcha();

    }

    //获取验证码
    private void getCaptcha(){
        if(mCaptcha!=null){
            return;
        }
        MySVProgressHUD.getInstance(this).showWithStatus("正在加载验证码");
        HttpRequest.getIntance().getCaptchaBitmap(new HttpRequest.IImageRequest() {
            @Override
            public void complete(Bitmap bitmap) {
                if (bitmap == null) {
                    ToastFactory.getToast(BoundLoginActivity.this, getResources().getString(R.string.connection_error)).show();
                    MySVProgressHUD.getInstance(BoundLoginActivity.this).dismiss();
                    return;
                }
                mCaptcha = bitmap;
                MySVProgressHUD.getInstance(BoundLoginActivity.this).dismiss();
            }
        });
    }

    public android.os.Handler handler=new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                //登录成功
                case MESSAGE_SUCCEED:
                    MySVProgressHUD.getInstance(BoundLoginActivity.this).dismiss();
                    finish();
                    break;
                //登录失败处理
                case MESSAGE_WRONG:
                    mCaptcha = null;
                    ToastFactory.getToast(BoundLoginActivity.this, LibraryRequest.getCodeType(msg.getData().getInt("code"))).show();
                    MySVProgressHUD.getInstance(BoundLoginActivity.this).dismiss();
                    getCaptcha();
                    break;
            }
        }
    };


    //检查账号密码是否正确
    public void checkUserIdAndPsw(final String id,final String libraryPsw){
        if(mCaptcha==null){
            getCaptcha();
            return;
        }
        MySVProgressHUD.getInstance(this).showWithStatus(getResources().getString(R.string.check_id));
        //识别验证码
        AutoGetCaptcha.getInstanse(BoundLoginActivity.this, mCaptcha).getCaptcha(new AutoGetCaptcha.IGetcaptchaListener() {
            @Override
            public void onComplete(String result) {
                //登录图书馆
                LibraryRequest.getInstance().loginByLibrary(BoundLoginActivity.this, id, libraryPsw, result, new LibraryRequest.ILoginListener() {
                    @Override
                    public void onSuccess(GKUser user) {
                        Log.i(TAG, "登录成功" + user.getUserName());
                        Message msg = new Message();
                        msg.what = MESSAGE_SUCCEED;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(int code) {
                        Log.i(TAG, "登录失败" + code);
                        Message msg = new Message();
                        msg.what = MESSAGE_WRONG;
                        Bundle bundle = new Bundle();
                        bundle.putInt("code",code);
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    }
                });
            }

            //识别验证码失败
            @Override
            public void onError(Exception e) {
                Log.i(TAG, "onError: 识别验证码失败");
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bound_login_close_btn:
                finish();
                break;
            //绑定
            case R.id.bound_save_btn:
                final String userid;
                final String libraryPsw;
                final String officePsw;
                userid=mUseridEdit.getText().toString().trim();
                libraryPsw=mLibraryPswEdit.getText().toString().trim();
                officePsw=mOfficePswEdit.getText().toString().trim();
                if(userid.isEmpty()){
                    ToastFactory.getToast(BoundLoginActivity.this,getResources().getString(R.string.id_is_empty)).show();
                    return;
                }
                if(libraryPsw.isEmpty() && officePsw.isEmpty()){
                    ToastFactory.getToast(BoundLoginActivity.this,getResources().getString(R.string.both_is_empty)).show();
                    return;
                }
                checkUserIdAndPsw(userid,libraryPsw);
                break;
        }
    }


    @Override
    public void onBackPressed() {
        if(MySVProgressHUD.getInstance(this).isShowing()){
            MySVProgressHUD.getInstance(this).dismiss();
            return;
        }
        super.onBackPressed();
    }


}
